<!--  富文本渲染 -->
<template>
  <div ref="richText" class="rich-text" v-html="getContent"></div>
</template>

<script name="RichText" setup>
import { ref, computed, onMounted } from 'vue'
const props = defineProps({
  content: {
    type: String,
    default: '',
  },
})
let richText = ref(null)

onMounted(() => {
  // 富文本中a标签点击事件
  richText.value.addEventListener('click', (event) => {
    event.preventDefault()
    let tag = event.target
    if (tag.tagName === 'A') {
      if (tag.href) {
        window.open(tag.href)
      }
    } else if (tag.parentNode.tagName === 'A') {
      if (tag.parentNode.href) {
        window.open(tag.parentNode.href)
      }
    }
  })
})

const getContent = computed(() => {
  let newContent = props.content
  // console.log(newContent)
  // let newContent = props.content.replace(
  //   /<img[^>]*>/gi,
  //   function (match, capture) {
  //     match = match
  //       .replace(/style="[^"]+"/gi, '')
  //       .replace(/style='[^']+'/gi, '')
  //     match = match
  //       .replace(/width="[^"]+"/gi, '')
  //       .replace(/width='[^']+'/gi, '')
  //     match = match
  //       .replace(/height="[^"]+"/gi, '')
  //       .replace(/height='[^']+'/gi, '')
  //     return match
  //   }
  // )
  // newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
  //   match = match
  //     .replace(/<p>/gi, '<p class="p_class">')
  //     .replace(/width:[^;]+;/gi, 'max-width:100%;')
  //     .replace(/width:[^;]+;/gi, 'max-width:100%;')
  //   return match
  // })
  if (newContent) {
    // newContent = newContent.replace(/<br[^>]*\/>/gi, '')
    newContent = newContent.replace(/<a/gi, '<a class="a_class"')
    newContent = newContent.replace(/<li/gi, '<li class="li_class"')
    newContent = newContent.replace(/<p/gi, '<p class="p_class"')
    newContent = newContent.replace(
      // eslint-disable-next-line no-useless-escape
      /\<img/gi,
      '<img class="img_class"'
    )
    newContent = newContent.replace(/(\r\n|\n|\r|↵)/g, '<br/>')
  }
  return newContent
})
</script>

<style scoped>
.rich-text {
  font-size: 16px;
  line-height: 26px;
  color: #666666;
  word-break: break-all;
}
.rich-text:deep(.img_class) {
  max-width: 100%;
  margin-top: 0;
  margin-bottom: 0;
  object-fit: scale-down;
}
.rich-text:deep(a) {
  text-decoration: underline;
  color: rgba(32, 110, 242, 1);
}
</style>
